package com.leo.common.security.server.handler;

import com.leo.common.core.enums.ExceptionCodeEnum;
import com.leo.common.security.server.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.web.HttpRequestMethodNotSupportedException;

/**
 * <p>
 * CustomWebResponseExceptionTranslator
 * </p>
 *
 * @author ：Leo
 * @since ：2021-04-06 15:29
 */
@Slf4j
public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {

	private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

	@Override
	public ResponseEntity<OAuth2Exception> translate(Exception e) {
		log.error("授权服务器 异常统一处理:异常:{}", e.getMessage(), e);
		// Try to extract a SpringSecurityException from the stacktrace
		Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);

		Exception ase = (AuthenticationException) throwableAnalyzer
				.getFirstThrowableOfType(AuthenticationException.class, causeChain);
		if (ase != null) {
			return handleOauth2Exception(new CustomUnauthorizedException(e.getMessage(), e),
					ExceptionCodeEnum.AUTH_UNAUTHORIZED.getCode());
		}
		ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class,
				causeChain);
		if (ase != null) {
			return handleOauth2Exception(new ForbiddenException(ase.getMessage(), ase),
					ExceptionCodeEnum.AUTH_FORBIDDEN_EXCEPTION.getCode());
		}

		ase = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class,
				causeChain);
		if (ase != null) {
			return handleOauth2Exception(new InvalidException(ase.getMessage(), ase),
					ExceptionCodeEnum.AUTH_INVALID_EXCEPTION.getCode());
		}

		ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
				.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
		if (ase != null) {
			return handleOauth2Exception(new MethodNotAllowedException(ase.getMessage(), ase),
					ExceptionCodeEnum.AUTH_METHOD_NOT_ALLOWED.getCode());
		}

		ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);

		if (ase != null) {
			return handleOauth2Exception((OAuth2Exception) ase, ExceptionCodeEnum.AUTH_EXCEPTION.getCode());
		}
		ase = (BadCredentialsException) throwableAnalyzer.getFirstThrowableOfType(BadCredentialsException.class,
				causeChain);

		if (ase != null) {
			return handleOauth2Exception((OAuth2Exception) ase,
					ExceptionCodeEnum.AUTH_BAD_CREDENTIALS_EXCEPTION.getCode());
		}

		return handleOauth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e),
				ExceptionCodeEnum.AUTH_SERVER_ERROR_EXCEPTION.getCode());

	}

	private ResponseEntity<OAuth2Exception> handleOauth2Exception(OAuth2Exception e, Integer code) {
		int status = e.getHttpErrorCode();
		HttpHeaders headers = new HttpHeaders();
		headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
		headers.set(HttpHeaders.PRAGMA, "no-cache");
		if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
			headers.set(HttpHeaders.WWW_AUTHENTICATE,
					String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
		}

		// 客户端异常直接返回客户端,不然无法解析
		if (e instanceof ClientAuthenticationException) {
			return new ResponseEntity<>(e, headers, HttpStatus.valueOf(status));
		}
		return new ResponseEntity<>(new Auth2Exception(e.getMessage(), e.getOAuth2ErrorCode(), code), headers,
				HttpStatus.valueOf(status));

	}

}
